package tree;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public abstract class XTree {
    public static int NULL = -86452875; // 为了简化，使用一个不常用数字代表空值

    public static void traverseLevel(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            TreeNode cur = q.poll();
            System.out.println(cur.val);
            if (cur.left != null) {
                q.offer(cur.left);
            }
            if (cur.right != null) {
                q.offer(cur.right);
            }
        }
    }

    public static TreeNode createTreeNode(int[] arr) {
        System.out.println("输入" + Arrays.toString(arr));

        if (arr == null) {
            return null;
        }
        TreeNode root = new TreeNode(arr[0]);
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);


        for (int i = 1; i < arr.length; ) {
            TreeNode parent = q.poll();
            int left = arr[i];
            System.out.println("left = " + left);
            if (left != NULL) {
                parent.left = new TreeNode(left);
                q.offer(parent.left);
            } else {
                parent.left = null;
            }
            i++;
            if (i >= arr.length) {
                break;
            }
            int right = arr[i];
            System.out.println("right = " + right);
            if (right != NULL) {
                parent.right = new TreeNode(right);
                q.offer(parent.right);
            } else {
                parent.right = null;
            }
            i++;
        }
        return root;
    }


    /**
     * 打印缩进，方便调试
     * 递归函数开头调用 printIndent（count++）
     * 所有return之前调用printIndent（--count）
     *
     * @param n
     */
    public static void printIndent(int n) {
        for (int i = 0; i < n; i++) {
            System.out.print("   ");
        }
    }
}
